"""
审计日志数据模型
"""
from tortoise import fields
from app.models.base.base import BaseModel

class AuditLog(BaseModel):
    """审计日志模型"""
    user_id = fields.IntField(description="用户ID", index=True)
    username = fields.CharField(max_length=64, default="", description="用户名称", index=True)
    module = fields.CharField(max_length=64, default="", description="功能模块", index=True)
    summary = fields.CharField(max_length=128, default="", description="请求描述", index=True)
    method = fields.CharField(max_length=10, default="", description="请求方法", index=True)
    path = fields.CharField(max_length=255, default="", description="请求路径", index=True)
    status = fields.IntField(default=-1, description="状态码", index=True)
    response_time = fields.IntField(default=0, description="响应时间(单位ms)", index=True)
    request_args = fields.JSONField(null=True, description="请求参数")
    response_body = fields.JSONField(null=True, description="返回数据")
    
    # 额外的审计信息
    ip_address = fields.CharField(max_length=45, null=True, description="客户端IP地址")
    user_agent = fields.TextField(null=True, description="用户代理信息")
    referer = fields.CharField(max_length=255, null=True, description="来源页面")

    class Meta:
        table = "audit_log"
        table_description = "系统审计日志表"
        
    def __str__(self):
        return f"AuditLog(id={self.id}, user={self.username}, method={self.method}, path={self.path})"
    
    @classmethod
    async def log_request(cls, user_id: int, username: str, module: str, summary: str, 
                         method: str, path: str, status: int, response_time: int,
                         request_args: dict = None, response_body: dict = None,
                         ip_address: str = None, user_agent: str = None, referer: str = None):
        """记录请求日志"""
        return await cls.create(
            user_id=user_id,
            username=username,
            module=module,
            summary=summary,
            method=method,
            path=path,
            status=status,
            response_time=response_time,
            request_args=request_args,
            response_body=response_body,
            ip_address=ip_address,
            user_agent=user_agent,
            referer=referer
        )
    
    @classmethod
    async def get_user_logs(cls, user_id: int, limit: int = 100):
        """获取用户操作日志"""
        return await cls.filter(user_id=user_id).order_by('-created_at').limit(limit)
    
    @classmethod
    async def get_error_logs(cls, limit: int = 100):
        """获取错误日志"""
        return await cls.filter(status__gte=400).order_by('-created_at').limit(limit)
    
    @classmethod
    async def get_slow_logs(cls, threshold: int = 1000, limit: int = 100):
        """获取慢请求日志"""
        return await cls.filter(response_time__gte=threshold).order_by('-response_time').limit(limit)